<?php

namespace app\admin\controller\ykjp\inventory;

use app\common\controller\Backend;
use think\Db;

/**
 * 调拨单
 *
 * @icon fa fa-circle-o
 */
class Transfer extends Backend {

    /**
     * Transfer模型对象
     * @var \app\admin\model\ykjp\inventory\Transfer
     */
    protected $model = null;
    protected $distinguish = true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\inventory\Transfer;
    }

    /**
     * 添加调拨单
     */
    public function add() {
        if ($this->request->isAjax()) {
            $request = $this->request->request();  //获取参数
            //验证参数
            if (!$request['row']['out_warehouse_id']) {
                $this->error('请选择调出仓库', null, null);
            } elseif (!$request['row']['out_partition_id']) {
                $this->error('请选择调出库区', null, null);
            } elseif (!$request['row']['product_id']) {
                $this->error('请选择调拨商品', null, null);
            } elseif ($request['row']['out_before_num'] == '') {
                $this->error('参数不完整1', null, null);  //调出前库存
            } elseif (!$request['row']['e_warehouse_id']) {
                $this->error('请选择调入仓库', null, null);
            } elseif (!$request['row']['e_partition_id']) {
                $this->error('请选择调入库区', null, null);
            } elseif ($request['row']['e_before_num'] == '') {
                $this->error('参数不完整2', null, null);  //调入前库存
            } elseif (!$request['row']['number']) {
                $this->error('请输入调拨数量', null, null);
            }

            //判断调拨库存是否充足
            if ($request['row']['number'] > $request['row']['out_before_num']) {
                $this->error('调出库存不足', null, null);
            }

            $request['row']['updatetime'] = time();           //设置更新时间
            $request['row']['firmid'] = $this->auth->firmid;  //设置企业ID

            $out_warehouse_id = $request['row']['out_warehouse_id'];  //调出仓库ID
            $out_partition_id = $request['row']['out_partition_id'];  //调出库区ID
            $product_id = $request['row']['product_id'];              //商品ID
            $out_before_num = $request['row']['out_before_num'];      //调出前数量
            $e_warehouse_id = $request['row']['e_warehouse_id'];      //调入仓库ID
            $e_partition_id = $request['row']['e_partition_id'];      //调入库区ID
            $e_before_num = $request['row']['e_before_num'];          //调入前数量
            $number = $request['row']['number'];                      //调拨数量
            $remark = $request['row']['remark'];                      //备注
            $updatetime = time();                                     //更新时间
            $firmid = $this->auth->firmid;                            //企业ID

            halt($request['row']);
            //更新调入关联表/新增调入关联表
            $e_wp = Db::name('ykjp_wp_relationship')->field('id')->where(['warehouse_id' => $e_warehouse_id, 'partition_id' => $e_partition_id, 'product_id' => $product_id])->where("firmid", $this->auth->firmid)->find();
            if ($e_wp) {
                //如果当前调入仓库商品存在关联表数据,则更新关联表数据
                halt(1);
            } else {
                //如果不存在当前调入仓库商品存在关联表数据,则插入关联表数据
                Db::name('ykjp_wp_relationship')->insert([
                    'warehouse_id' => $e_warehouse_id,
                    'partition_id' => $e_partition_id,
                    'product_id' => $product_id,
                    'inventory' => $number,
                    'updatetime' => $updatetime,
                    'firmid' => $firmid
                ]);
            }
            halt(3);


            halt(123123);
            //提交数据（插入调拨表->插入流水表（调拨出库和调拨入库）->更新调出关联表->更新调入关联表/新增调入关联表->更新（出入库）仓库表->更新（出入库）库区表）
            // 启动事务
            Db::startTrans();
            try {

                //插入调拨表 ok
                Db::name('ykjp_transfer')->insert($request['row']);

                //插入调拨出库流水表
                Db::name('ykjp_inventory_statement')->insert([
                    'product_id' => $product_id,
                    'warehouse_id' => $out_warehouse_id,
                    'partition_id' => $out_partition_id,
                    'number' => $number,
                    'type' => '调拨出库',
                    'updatetime' => $updatetime,
                    'firmid' => $firmid
                ]);

                //插入调拨入库流水表
                Db::name('ykjp_inventory_statement')->insert([
                    'product_id' => $product_id,
                    'warehouse_id' => $e_warehouse_id,
                    'partition_id' => $e_partition_id,
                    'number' => $number,
                    'type' => '调拨入库',
                    'updatetime' => $updatetime,
                    'firmid' => $firmid
                ]);

                // 更新调出关联表
                Db::name('ykjp_wp_relationship')->where(['warehouse_id' => $out_warehouse_id, 'partition_id' => $out_partition_id, 'product_id' => $product_id])->where("firmid", $this->auth->firmid)->update([
                    'updatetime' => time(),
                    'inventory' => Db::raw('inventory-' . $number),
                ]);

                //更新关联表 
                $data['inventory'] = array('exp', 'inventory' . $op . $number);
                $data['updatetime'] = time();
                Db::name('ykjp_wp_relationship')->where(['warehouse_id' => $warehouse_id, 'partition_id' => $partition_id, 'product_id' => $product_id])->where("firmid", $this->auth->firmid)->update([
                    'updatetime' => time(),
                    'inventory' => Db::raw('inventory' . $op . $number),
                ]);

                //更新商品表
                Db::name('ykjp_product')->where("firmid", $this->auth->firmid)->where('id', $product_id)->$fun('inventory', $number);

                //更新仓库表
                Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->where('id', $warehouse_id)->$fun('inventory', $number);

                //更新库区表
                Db::name('ykjp_partition')->where("firmid", $this->auth->firmid)->where('id', $partition_id)->$fun('inventory', $number);

                // 提交事务
                Db::commit();
                $this->success('提交成功', null, null);
            } catch (PDOException $e) {

                Db::rollback();
                $this->error('提交失败');
            } catch (Exception $e) {

                Db::rollback();
                $this->error('提交失败');
            }
        }
        return $this->view->fetch('add');
    }

    /**
     * 获取仓库列表
     */
    public function warehouse() {
        $warehouselist = Db::name('ykjp_warehouse')->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
        $this->success('', null, $warehouselist);
    }

    /**
     * 获取分区列表
     */
    public function partition() {
        $id = $this->request->request('id');
        $partitionlist = Db::name('ykjp_partition')->where('warehouse_id', $id)->where("firmid", $this->auth->firmid)->field('id as value,name')->order('id desc')->select();
        $this->success('', null, $partitionlist);
    }

    /**
     * 获取产品列表
     */
    public function product() {
        $id = $this->request->request('id');
        $productlist = Db::name('ykjp_product')
                ->alias('p')
                ->join('ykjp_wp_relationship w', 'w.product_id = p.id')
                ->field('p.id as value,p.name')
                ->where('w.partition_id', $id)
                ->where("w.firmid", $this->auth->firmid)
                ->select();
        $this->success('', null, $productlist);
    }

    /**
     * 获取账面库存
     */
    public function get_num() {
        $where = $this->request->request();
        $surface_num = Db::name('ykjp_wp_relationship')
                ->field('inventory')
                ->where($where)
                ->where("firmid", $this->auth->firmid)
                ->find();
        $this->success('', null, $surface_num);
    }

}
